package com.example.demo.testWeb;

import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;



@Service
public class TestWebService {

    public ResponseEntity<?> testResponseEntity(MultipartFile file) throws IOException {
        InputStreamReader reader = new InputStreamReader(file.getInputStream(), "UTF-8");
        BufferedReader br = new BufferedReader(reader);
        String line = "";
        Boolean hasNextLine = true;
//        ComeInAndGoOutPrison comeInAndGoOutPrison;
        line = br.readLine();
        List<String> abnormalData = new ArrayList<String>();
/*        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS");
        while (hasNextLine) {

            try {
                line = br.readLine();
                if (line == null) {
                    hasNextLine = false;
                    break;
                }
                int b = 1/0;
            } catch (Exception e) {
                e.printStackTrace();
                abnormalData.add(line);
                abnormalData.add("\n");
                abnormalData.add(e.toString());
                abnormalData.add("\n");
                abnormalData.add("\n");
            }

        }
        br.close();*/

        abnormalData.add("aa");
        abnormalData.add("bb");
        abnormalData.add("cc");
        if (abnormalData.size() > 0) {
            System.out.println(abnormalData);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            for (String item : abnormalData) {
                baos.write(item.getBytes());
            }

            ByteArrayResource byteArrayResource = new ByteArrayResource(baos.toByteArray());

            return ResponseEntity
                    .ok()
                    .contentLength(byteArrayResource.contentLength())
                    .header("","")
                    .contentType(MediaType.TEXT_PLAIN)
                    .body(byteArrayResource);
        } else {
            return ResponseEntity.ok().build();
        }

    }

    public ResponseEntity<?> cc() throws UnsupportedEncodingException, FileNotFoundException {
        String fileName="aa.txt";
      return   ResponseEntity
                .ok().
                header("Content-Disposition", "attachment;filename="+ new String((fileName).getBytes(), "UTF-8"))
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new FileOutputStream(new File("D:/aa.txt")));
    }
}
